<?php

class Lib_Request_Curl
{

    /**
     * @param $url
     * @param string $params
     * @param int    $timeout
     *
     * @return array|mixed
     */
    public static function postjson($url, $params = '', $header = [], $timeout = 30, $file = '')
    {
        $logs = ' request_url='.$url;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);

        $log = array();
        $res = curl_exec($ch);
        $log['errno'] = curl_errno($ch);
        if ($log['errno'] !== 0) {
            curl_close($ch);
            $result['error'] = $log['errno'];
            Func_Log::write('curl_postjson', 'curl_response401', $logs.json_encode($log).$res);
            return $result;
        }
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $res = substr($res, $header_size);
        curl_close($ch);
        if(!json_decode($res,true)){
            Func_Log::write('curl_postjson', 'curl_response500', $logs.json_encode($log).$res);
            $result['error'] = 500;
            return $result;
        }
        $res = json_decode($res,true);
        $res['error'] = 200;

        return $res;
    }
}
